package dao;

import entity.IEntity;
import entity.Teacher;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.NonUniqueResultException;
import javax.persistence.Query;
import javax.persistence.criteria.CriteriaQuery;

/**
 *
 * @author Alexander
 */
public class TeacherDAO implements IDAO {

    @Override
    public void persist(IEntity entity, EntityManager em) {
        em.persist(entity);
    }

    @Override
    public IEntity find(Object id, EntityManager em) {
        return (Teacher) em.find(Teacher.class, (int) id);
    }

    @Override
    public void update(IEntity entity, EntityManager em) {
        em.merge(entity);
    }

    @Override
    public void delete(Object id, EntityManager em) {
        Teacher prof = em.getReference(Teacher.class, (int) id);
        em.remove(prof);
    }

    @Override
    public List<IEntity> getList(EntityManager em) {
        CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
        cq.select(cq.from(Teacher.class));
        Query q = em.createQuery(cq);
        return q.getResultList();
    }

    public Teacher findByName(String nombre, String apellido, EntityManager em) {
        Teacher teacher = null;
        Query q = em.createQuery("SELECT p from Teacher p "
                + "WHERE p.name LIKE :nombre"
                + " AND p.lastName LIKE :apellido").setParameter("nombre", nombre).setParameter("apellido", apellido);
        try {
            teacher = ((Teacher) q.getSingleResult());
        } catch (NonUniqueResultException e) {
            teacher = ((Teacher) q.getResultList().get(0));
        }
        return teacher;
    }
}
